//
//  LVMediaSuperViewController.m
//  LEVE
//
//  Created by 王若聪 on 2016/12/12.
//  Copyright © 2016年 dashuju. All rights reserved.
//

#import "LVMediaSuperViewController.h"
#import <Masonry.h>
#import "JotTextView.h"
#import "IQKeyboardManager.h"
//贴纸页面
#import "CustomTableView.h"
#import "CustomCollectionView.h"
#import "CustomSegmentControl.h"
#import "UIView+STFrame.h"
#import <objc/message.h>
#import "Emoji.h"

#define RGBColorAlpha(r,g,b,f)   [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:f]
#define RGBColor(r,g,b)          RGBColorAlpha(r,g,b,1)

@interface LVMediaSuperViewController ()<JotViewControllerDelegate,SwipeTableViewDataSource,SwipeTableViewDelegate,UIGestureRecognizerDelegate,UIViewControllerTransitioningDelegate>
//贴纸
@property (nonatomic, strong) CustomSegmentControl  * segmentBar;
@property (nonatomic, strong) CustomTableView       * tableView;
@property (nonatomic, strong) CustomCollectionView  * collectionView;
@property (nonatomic, strong) NSMutableDictionary   * dataDic;
@end

@implementation LVMediaSuperViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    UITapGestureRecognizer *tapbackgroundRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBackground:)];
//    [tapbackgroundRecognizer setNumberOfTapsRequired:1];
//    [self.view addGestureRecognizer:tapbackgroundRecognizer];
    
}
- (void)setupJotViewController{
    if (!_jotViewController) {
        _jotViewController = [JotViewController new];
        
        self.jotViewController.delegate = self;
        self.jotViewController.state = JotViewStateText;
        self.jotViewController.textColor = [UIColor whiteColor];
        self.jotViewController.font = [UIFont boldSystemFontOfSize:24.f];
        self.jotViewController.fontSize = 24.f;
        self.jotViewController.textEditingInsets = UIEdgeInsetsMake(212.f, 6.f, 0.f, 6.f);
        self.jotViewController.initialTextInsets = UIEdgeInsetsMake(6.f, 6.f, 6.f, 6.f);
        self.jotViewController.fitOriginalFontSizeToViewWidth = YES;
        self.jotViewController.textAlignment = NSTextAlignmentLeft;
        self.jotViewController.drawingColor = [UIColor cyanColor];
        
        self.jotViewController.drawingStrokeWidth = 20.f;
        self.jotViewController.drawingConstantStrokeWidth = YES;
        
        
        [self addChildViewController:self.jotViewController];
        [self.view addSubview:self.jotViewController.view];
        [self.jotViewController didMoveToParentViewController:self];
        [self.jotViewController.view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
    }
}

- (void)cancelButtonPressed:(UIButton *)button {
    
    if (self.swipeTableView) {
        self.swipeTableView.hidden = YES;
        [self.swipeTableView removeFromSuperview];
        self.swipeTableView = nil;
        [self.cancelButton setImage:[UIImage imageNamed:@"cancel.png"] forState:UIControlStateNormal];
    }else{
        [self dismissViewControllerAnimated:NO completion:nil];
    }
    
}

- (void)imageButtonPressed:(UIButton *)button {
    
    
    BOOL disableBarScroll = YES;
    BOOL hiddenNavigationBar = YES;
    
    // init swipetableview
    self.swipeTableView = [[SwipeTableView alloc]initWithFrame:self.view.bounds];
    //    self.swipeTableView.backgroundColor = [UIColor colorWithRed:65/255.0 green:65/255.0 blue:68/255.0 alpha:0.8];
    self.swipeTableView.delegate = self;
    self.swipeTableView.dataSource = self;
    self.swipeTableView.shouldAdjustContentSize = YES;
    self.swipeTableView.swipeHeaderBar = self.segmentBar;
    self.swipeTableView.swipeHeaderBarScrollDisabled = disableBarScroll;
    
    if (hiddenNavigationBar) {
        self.swipeTableView.swipeHeaderTopInset = 0;
    }
    
    [self.view addSubview:_swipeTableView];
    
    // edge gesture
    //    [_swipeTableView.contentView.panGestureRecognizer requireGestureRecognizerToFail:self.screenEdgePanGestureRecognizer];
    
    // init data
    _dataDic = [@{} mutableCopy];
    
    // 根据滚动后的下标请求数据
    [self getDataAtIndex:0];
    
    // 一次性请求所有item的数据
    //    [self getAllData];
    
    
    [self.cancelButton setImage:[UIImage imageNamed:@"camera_return"] forState:UIControlStateNormal];
    
    
    
}

- (void)labelButtonPressed:(UIButton *)button {
    
    if (self.swipeTableView) {
        self.swipeTableView.hidden = YES;
        [self.swipeTableView removeFromSuperview];
        self.swipeTableView = nil;
    }
}

- (void)drawButtonPressed:(UIButton *)button {
    [self setupJotViewController];
    self.jotViewController.state = JotViewStateDrawing;
    self.jotViewController.drawingColor = [UIColor colorWithRed:((double)arc4random()/UINT32_MAX) green:((double)arc4random()/UINT32_MAX) blue:((double)arc4random()/UINT32_MAX) alpha:1.0];
    
    if (self.swipeTableView) {
        self.swipeTableView.hidden = YES;
        [self.swipeTableView removeFromSuperview];
        self.swipeTableView = nil;
    }
}

- (void)saveButtonPressed:(UIButton *)button {
    NSLog(@"save button clicked");
    
}
- (void)sendButtonPressed:(UIButton *)button {
    

}


//- (void)tapBackground:(UITapGestureRecognizer *)recognizer {

    
    //这里有点问题 需要确认下 点击屏幕是否要开始输入文字
    
//    if (!self.jotViewController) {
//        //        [self setupJotViewController];
//        //        self.jotViewController.state = JotViewStateText;
//        
//    }else{
//        //点击屏幕弹出输入文字label
//        if (self.jotViewController.textString.length == 0) {
//            self.jotViewController.state = JotViewStateEditingText;
//        } else {
//            self.jotViewController.state = JotViewStateText;
//        }
//    }
    
    
//}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    [self.cancelButton addTarget:self action:@selector(cancelButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    self.cancelButton.frame = CGRectMake(0, 5, 44, 44);
    [self.view addSubview:self.cancelButton];
    
    [self.imageButton addTarget:self action:@selector(imageButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    self.imageButton.frame = CGRectMake(self.view.bounds.size.width - 150, self.cancelButton.top, 44, 44);
    [self.view addSubview:self.imageButton];
    
    [self.labelButton addTarget:self action:@selector(labelButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    self.labelButton.frame = CGRectMake(self.view.bounds.size.width - 100 ,self.cancelButton.top, 44, 44);
    [self.view addSubview:self.labelButton];
    
    [self.drawButton addTarget:self action:@selector(drawButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    self.drawButton.frame = CGRectMake(self.view.bounds.size.width - 50 ,self.cancelButton.top, 44, 44);
    [self.view addSubview:self.drawButton];
    
    [self.saveButton addTarget:self action:@selector(saveButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    self.saveButton.frame = CGRectMake(0 ,self.view.bounds.size.height - 70, 50, 70);
    [self.view addSubview:self.saveButton];

    [self.sendButton addTarget:self action:@selector(sendButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    self.sendButton.frame = CGRectMake(self.view.bounds.size.width - 73,self.view.bounds.size.height - 73 , 73, 73);
    [self.view addSubview:self.sendButton];

    
    if (self.swipeTableView) {
        //        [self.view bringSubviewToFront:self.segmentBar];
        
        //        self.cancelButton.hidden = YES;
        self.saveButton.hidden = YES;
        
        
    }else{
    
        self.saveButton.hidden = NO;
    }
    
}

- (UIButton *)cancelButton {
    if(!_cancelButton) {
        UIImage *cancelImage = [UIImage imageNamed:@"cancel.png"];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.tintColor = [UIColor whiteColor];
        [button setImage:cancelImage forState:UIControlStateNormal];
        button.imageView.clipsToBounds = NO;
        //        button.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
        button.layer.shadowColor = [UIColor blackColor].CGColor;
        button.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
        button.layer.shadowOpacity = 0.4f;
        button.layer.shadowRadius = 1.0f;
        button.clipsToBounds = NO;
        _cancelButton = button;
    }
    return _cancelButton;
}
- (UIButton *)imageButton {
    if(!_imageButton) {
        UIImage *cancelImage = [UIImage imageNamed:@"camera_ex"];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.tintColor = [UIColor whiteColor];
        [button setImage:cancelImage forState:UIControlStateNormal];
        button.imageView.clipsToBounds = NO;
        //        button.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
        button.layer.shadowColor = [UIColor blackColor].CGColor;
        button.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
        button.layer.shadowOpacity = 0.4f;
        button.layer.shadowRadius = 1.0f;
        button.clipsToBounds = NO;
        _imageButton = button;
    }
    return _imageButton;
}
- (UIButton *)labelButton {
    if(!_labelButton) {
        UIImage *cancelImage = [UIImage imageNamed:@"camera_word"];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.tintColor = [UIColor whiteColor];
        [button setImage:cancelImage forState:UIControlStateNormal];
        button.imageView.clipsToBounds = NO;
        //        button.contentEdgeInsets = UIEdgeInsetsMake(4, 4, 4, 4);
        button.layer.shadowColor = [UIColor blackColor].CGColor;
        button.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
        button.layer.shadowOpacity = 0.4f;
        button.layer.shadowRadius = 1.0f;
        button.clipsToBounds = NO;
        _labelButton = button;
    }
    return _labelButton;
}
- (UIButton *)drawButton {
    if(!_drawButton) {
        UIImage *cancelImage = [UIImage imageNamed:@"camera_pen"];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.tintColor = [UIColor whiteColor];
        [button setImage:cancelImage forState:UIControlStateNormal];
        button.imageView.clipsToBounds = NO;
        //        button.contentEdgeInsets = UIEdgeInsetsMake(7, 7, 7, 7);
        button.layer.shadowColor = [UIColor blackColor].CGColor;
        button.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
        button.layer.shadowOpacity = 0.4f;
        button.layer.shadowRadius = 1.0f;
        button.clipsToBounds = NO;
        _drawButton = button;
    }
    return _drawButton;
}

- (UIButton *)saveButton {
    if(!_saveButton) {
        UIImage *saveImage = [UIImage imageNamed:@"camera_download"];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.tintColor = [UIColor whiteColor];
        [button setImage:saveImage forState:UIControlStateNormal];
        button.imageView.clipsToBounds = NO;
        //        button.contentEdgeInsets = UIEdgeInsetsMake(7, 7, 7, 7);
        button.layer.shadowColor = [UIColor blackColor].CGColor;
        button.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
        button.layer.shadowOpacity = 0.4f;
        button.layer.shadowRadius = 1.0f;
        button.clipsToBounds = NO;
        _saveButton = button;
    }
    return _saveButton;
}
- (UIButton *)sendButton
{
    if (!_sendButton) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setImage:[UIImage imageNamed:@"camera_send"] forState:UIControlStateNormal];
        _sendButton = btn;
    }
    return _sendButton;
}
- (BOOL)prefersStatusBarHidden {
    return YES;
}

#pragma mark 贴纸相关
- (UIScreenEdgePanGestureRecognizer *)screenEdgePanGestureRecognizer {
    UIScreenEdgePanGestureRecognizer *screenEdgePanGestureRecognizer = nil;
    if (self.navigationController.view.gestureRecognizers.count > 0) {
        for (UIGestureRecognizer *recognizer in self.navigationController.view.gestureRecognizers) {
            if ([recognizer isKindOfClass:[UIScreenEdgePanGestureRecognizer class]]) {
                screenEdgePanGestureRecognizer = (UIScreenEdgePanGestureRecognizer *)recognizer;
                break;
            }
        }
    }
    return screenEdgePanGestureRecognizer;
}

#pragma mark - Header & Bar

- (CustomSegmentControl * )segmentBar {
    if (nil == _segmentBar) {
        self.segmentBar = [[CustomSegmentControl alloc]initWithItemsUsingImageNames:@[@"camera_star",@"camera_prop",@"camera_funny",@"camera_animal",@"camera_album"]];
        _segmentBar.st_size = CGSizeMake(kScreenWidth, 40);
        _segmentBar.backgroundColor = RGBColor(65, 65, 68);
        _segmentBar.selectionIndicatorColor = [UIColor clearColor];
        
        
        _segmentBar.selectedSegmentIndex = _swipeTableView.currentItemIndex;
        [_segmentBar addTarget:self action:@selector(changeSwipeViewIndex:) forControlEvents:UIControlEventValueChanged];
    }
    return _segmentBar;
}

- (CustomTableView *)tableView {
    if (nil == _tableView) {
        _tableView = [[CustomTableView alloc]initWithFrame:_swipeTableView.bounds style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor colorWithRed:65/255.0 green:65/255.0 blue:68/255.0 alpha:0.95];
        
    }
    return _tableView;
}

- (CustomCollectionView *)collectionView {
    if (nil == _collectionView) {
        _collectionView = [[CustomCollectionView alloc]initWithFrame:_swipeTableView.bounds];
        _collectionView.backgroundColor = [UIColor colorWithRed:65/255.0 green:65/255.0 blue:68/255.0 alpha:0.95];
        
    }
    return _collectionView;
}

- (void)changeSwipeViewIndex:(UISegmentedControl *)seg {
    [_swipeTableView scrollToItemAtIndex:seg.selectedSegmentIndex animated:NO];
    
    // request data at current index
    [self getDataAtIndex:seg.selectedSegmentIndex];
}

#pragma mark - Data Reuqest

// 请求数据（根据视图滚动到相应的index后再请求数据）
- (void)getDataAtIndex:(NSInteger)index {
    if (nil != _dataDic[@(index)]) {
        return;
    }
    NSInteger numberOfRows = 0;
    switch (index) {
        case 0:
            self.collectionView.allEmojiArray = [Emoji allEmoji];
            
            numberOfRows = self.collectionView.allEmojiArray.count;
            break;
        case 1:
            numberOfRows = 12;
            
            break;
        case 2:
            numberOfRows = 12;
            break;
        case 3:
            numberOfRows = 12;
            break;
        case 4:
            numberOfRows = 12;
            break;
        default:
            break;
    }
    // 请求数据后刷新相应的item
    ((void (*)(void *, SEL, NSNumber *, NSInteger))objc_msgSend)((__bridge void *)(self.swipeTableView.currentItemView),@selector(refreshWithData:atIndex:), @(numberOfRows),index);
    // 保存数据
    [_dataDic setObject:@(numberOfRows) forKey:@(index)];
}

// 请求数据（一次性获取所有item的数据）
- (void)getAllData {
    
    //    [_dataDic setObject:@(12) forKey:@(0)];
    //    [_dataDic setObject:@(120) forKey:@(1)];
    //    [_dataDic setObject:@(12) forKey:@(2)];
    //    [_dataDic setObject:@(12) forKey:@(3)];
    
}


#pragma mark - SwipeTableView M
- (void)swipeTableView:(SwipeTableView *)swipeView didSelectItemAtIndex:(NSInteger)index{

    //不知道为什么这个回调不调用 醉醉哒


}

- (NSInteger)numberOfItemsInSwipeTableView:(SwipeTableView *)swipeView {
    return 5;
}

- (UIScrollView *)swipeTableView:(SwipeTableView *)swipeView viewForItemAtIndex:(NSInteger)index reusingView:(UIScrollView *)view {
    
    // 混合的itemview只有同类型的item采用重用
    if (index == 0 || index == 2 || index == 4) {
        
        CustomCollectionView * collectionView = self.collectionView;
        
        // 获取当前index下item的数据，进行数据刷新
        id data = _dataDic[@(index)];
        [collectionView refreshWithData:data atIndex:index];
        
        
        
        self.collectionView.selectedStickerStringBlock = ^(NSString *string){
            
            NSLog(@"%@",string);
        };
       

        
        
        view = self.collectionView;
        
        
        
    }else {
        
        // 懒加载保证同样类型的item只创建一次，以达到重用
        CustomTableView * tableView = self.tableView;
        
        // 获取当前index下item的数据，进行数据刷新
        id data = _dataDic[@(index)];
        [tableView refreshWithData:data atIndex:index];
        
        view = tableView;
        
    }
    
    // 在没有设定下拉刷新宏的条件下，自定义的下拉刷新需要做 refreshheader 的 frame 处理
    //    [self configRefreshHeaderForItem:view];
    
    return view;
}

// swipetableView index变化，改变seg的index
- (void)swipeTableViewCurrentItemIndexDidChange:(SwipeTableView *)swipeView {
    _segmentBar.selectedSegmentIndex = swipeView.currentItemIndex;
}

// 滚动结束请求数据
- (void)swipeTableViewDidEndDecelerating:(SwipeTableView *)swipeView {
    [self getDataAtIndex:swipeView.currentItemIndex];
}

/**
 *  以下两个代理，在未定义宏 #define ST_PULLTOREFRESH_HEADER_HEIGHT，并自定义下拉刷新的时候，必须实现
 *  如果设置了下拉刷新的宏，以下代理可根据需要实现即可
 */
- (BOOL)swipeTableView:(SwipeTableView *)swipeTableView shouldPullToRefreshAtIndex:(NSInteger)index {
    return NO;
}


#pragma  mark - UIViewControllerTransitioningDelegate
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    __weak typeof(self) weakSelf = self;
    self.navigationController.interactivePopGestureRecognizer.delegate = weakSelf;
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    self.navigationController.interactivePopGestureRecognizer.delegate = nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
